package com.mt.roll.core.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.tools.imageio.ImageIOUtil;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * pdf转图片
 */
public class PDF2Img {
    /**
     * pdf转图片
     *
     * @param file 要转换的pdf文件
     * @return 转换之后的BufferedImage集合（图片个数取决于pdf页码个数）
     */
    public static List<Map<String, String>> changePdfToImg(String instructiopath, String basePath) throws Exception {
        List<Map<String, String>> mapList = new ArrayList<>();
        File file = new File(instructiopath);
        PDDocument doc = null;
        int pageCount = 0;
        int pdfDPI = 500;//图片质量
        try {
            doc = PDDocument.load(file);
            pageCount = doc.getNumberOfPages();
            System.out.println(pageCount);
            PDFRenderer pdfRenderer = new PDFRenderer(doc);
            File fileDir = new File(basePath);
            if (!fileDir.exists()) {
                // 目录不存在则创建
                fileDir.mkdirs();
            }
            for (int i = 0; i < pageCount; i++) {
                Map<String, String> map = new HashMap<>();
                String random18Str = DateUtil.getCurrentDateTime() + RandomCodeGenerator.numericCode(4);
                BufferedImage bim = pdfRenderer.renderImageWithDPI(i, pdfDPI,
                        ImageType.RGB);
                // suffix in filename will be used as the file format
                ImageIOUtil.writeImage(bim, basePath + "/" + random18Str
                        + ".jpg", pdfDPI);
                map.put("filePath", basePath + "/" + random18Str + ".jpg");
                map.put("fileName", random18Str);
                mapList.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (doc != null) {
                try {
                    doc.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return mapList;
    }

    public static void main(String[] args) {
        try {
            changePdfToImg("C:\\Users\\admin\\Desktop\\156512992382046445.pdf", "C:\\Users\\admin\\Desktop\\");
        } catch (Exception e) {

        }
    }
}